package com.atguigu.crowd.funding.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.atguigu.crowd.funding.entity.Menu;
import com.atguigu.crowd.funding.entity.ResultEntity;
import com.atguigu.crowd.funding.service.api.MenuService;
import com.fasterxml.jackson.databind.ser.std.StdKeySerializers.Default;

@RestController
public class MenuHandler {

	@Autowired
	private MenuService menuService;
	
	//获取所有菜单数据，并封装成树结构返回，即返回一个根节点
	@RequestMapping("/menu/get/rootnode")
	public ResultEntity<Menu> getRNode(){
		//1、获取所有菜单数据
		List<Menu> menus=menuService.getAllMenu();
		
		//2、组装根节点，即根节点包含子节点集合，一级子节点包含其对应的二级子节点集合。
		//2.1（效率优化）使用键值对存储每个节点所对应的子节点（pid,子节点集合）
		Map<Integer, List<Menu>> menutable=new HashMap<Integer,List<Menu>>();
		for (Menu menu : menus) {
			if(menu.getPid()==null)continue;
			
			if(menutable.containsKey(menu.getPid())){
				menutable.get(menu.getPid()).add(menu);
			}else{
				List<Menu> list=new ArrayList<Menu>();
				list.add(menu);
				menutable.put(menu.getPid(), list);
				}
		}
		
		//2.2找出根节点，并为每个节点赋其对应的子节点
		Menu rootNode=null;
		for (Menu menu : menus) {
			if(menu.getPid()==null)rootNode=menu;
			List<Menu> children=menutable.get(menu.getId());
			menu.setChildren(children);
			if(children!=null)
			menu.setLength(children.size());
		}
		
		return ResultEntity.successWithoutData(rootNode);
	}
	
	/**
	 * 增加
	 */
	@RequestMapping("/menu/add")
	public ResultEntity<String> addNode(Menu menu){
		menuService.saveNode(menu);
		return ResultEntity.successWithoutData();
	}
	
	
	/**
	 * 删除
	 */
	@RequestMapping("/menu/remove")
	public ResultEntity<String> removeNode(
			@RequestParam("menuid") Integer menuid){
		menuService.removeNode(menuid);
		return ResultEntity.successWithoutData();
	}
	/**
	 * 根据id查找
	 */
	@RequestMapping("/menu/get/Node")
	public ResultEntity<Menu> queryNode(
			@RequestParam(name="menuid") Integer menuid){
		Menu menu = menuService.getNodeById(menuid);
		return ResultEntity.successWithoutData(menu);
	}
	/**
	 * 修改
	 */
	@RequestMapping("/menu/update")
	public ResultEntity<String> updateNode(
			Menu menu){
		menuService.updateNode(menu);
		return ResultEntity.successWithoutData();
	}
}
